package com.library.controller.user;

import com.library.commen.properties.JwtProperties;
import com.library.commen.utils.JwtUtil;
import com.library.pojo.Result;
import com.library.pojo.User;
import com.library.service.LoginService;
import com.library.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;

@RestController("userLogin")
@RequestMapping("/user")
@Slf4j
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("login")
    public Result login(@RequestBody User user){
        log.info("用户{}登录",user.getUserName());
        User user1 = null;
        try {
            user1 = loginService.userLogin(user);
        } catch (Exception e) {
            return Result.error("用户名或密码错误");
        }
        if(user1 != null&&user1.getStatus()==1) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", user1.getId());
            claims.put("name", user1.getUserName());
            String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey()
                    ,jwtProperties.getUserTtl()
                    ,claims);
            return Result.success(jwt);
        }
        if(user1.getStatus()==0){
            return Result.error("该用户被禁用");
        }
        return Result.error("用户名或密码错误");
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        user.setStatus(1);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userService.register(user);
        return Result.success();
    }
}
